package com.css.apps.base.user.service;

import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import com.css.apps.base.org.model.SUserOrg;
import com.css.apps.base.user.model.SUser;
import com.css.core.configuration.Environment;
import com.css.db.query.TransactionCache;
import com.css.util.Md5Util;

public class UserMock {
	//组织业务数据
	public static SUser getModel() throws Exception{
		SUser item = new SUser();
		String name = getRandomString(16);
		item.setLoginName(name);
		item.setRealName(name);
		item.setOrgId("8a8d8149523a003401523a017a1d0003");
		item.setOpenFlag("1");
		item.setSex("1");
		item.setUserType("1");
		item.setSecLevel("1");
		item.setDelFlag(Environment.UN_DELETE_STATE);
		item.setIssueDate(new Date());
		item.setIssueId("1dd6d1b6f4624e4ce830408415681577");
		item.setIssueName("系统管理员");
		item.setEditDate(new Date());
		item.setTotalLoginCount(0);
		item.setFailedLoginCount(0);
		item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode("admin111111")));
		item.setActiveStatus("1");
		item.setFailedLoginCount(0);
		return item;
	}
	
	//业务处理
	public static void bizDeal(int count) throws Exception{
		for(int i=0;i<count;i++){
			TransactionCache tx = null;
			try {	
				long t1 = System.currentTimeMillis();
				tx = new TransactionCache();
				SUser user = getModel();
				tx.save(user);
				SUserOrg userorg = new SUserOrg();
				userorg.setOrgId(user.getOrgId());
				userorg.setUserId(user.getUuid());
				tx.save(userorg);
				tx.commit();
				long t2 = System.currentTimeMillis();
				if(user != null){
					System.out.println("添加用户成功 :" + user.getLoginName() + "," + (t2-t1) + " ms!");
				}
			} catch (Throwable e) {
				if(tx!=null)
					tx.rollback();
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args)throws Exception {
		int totalCount = 1000; //写入数据总数
		if(args != null && args.length > 0){
			totalCount=Integer.parseInt(args[0]);
		}	
		int threadCount = 10; //启动线程数
		if(args != null && args.length > 2){
			threadCount=Integer.parseInt(args[1]);
		}	
		if(threadCount < 1){
			threadCount=10;
		}
		int dealNum = totalCount/threadCount;
		BizThread[] threads = new BizThread[threadCount];
		for(int i=0;i<threadCount;i++){
			threads[i] = new BizThread(dealNum);
		}
		Pool pool = new Pool(threadCount,threads);
		pool.start(); //开始运行
		System.out.println("添加用户完成!");
	}
	
	public static class BizThread extends Thread{
		private SUser user;
		private int dealCount;
		private  boolean finished = false;
		
		public BizThread(int count){
			this.dealCount = count;
		}
		
		public void run(){
			try {
				bizDeal(dealCount);
				finished=true;
				System.out.println(user.getRealName()+"-"+"线程 " + Thread.currentThread().getName()+" 执行完毕!");
			} catch (Exception e) {						 
				e.printStackTrace();
				finished=true;
				System.out.println("线程" + Thread.currentThread().getName() + "异常退出!");
			} 
		}
		
		public boolean isFinished(){
			return this.finished;
		}
	}
	
	/****
	 * 仅仅控制并发执行的线程数
	 * @author paladin
	 *
	 */
	public static  class Pool {
		 private int capacity = 10;
		 private java.util.List<BizThread> threads = null;
		 private java.util.List<BizThread> runThreads = null;
		 public Pool(int cap,BizThread[] threads){
			 this.capacity=cap;	
			 this.threads = new java.util.LinkedList<BizThread>(Arrays.asList(threads));
			 this.runThreads = new java.util.LinkedList<BizThread>();
		 }
		 
		 public void start(){
			 //初始化
			 java.util.Iterator<BizThread> its=threads.iterator();
			 while(its.hasNext()){
				 BizThread th=its.next();
				 if(capacity<runThreads.size())
					 {
					 	runThreads.add(th);
					 	th.start();
					 	System.out.println("线程 " + th.getName()+" 启动!");
					 	//备选队列移除
					 	its.remove();
					 }
			 }
			 
			 //运行检查，每秒钟检查一次
			 int sleepTime =1000;
			 while(true)
			 {
				//执行完毕
				if(runThreads.isEmpty() && threads.isEmpty())
					break;
				 
				//检查运行队列
				its = runThreads.iterator();
				while(its.hasNext()){
					BizThread th=its.next();
					if(th.isFinished())
						its.remove();
				}
				 
				//往运行队列中添加线程
				if(!threads.isEmpty()){					 
					int runThrs=this.capacity - runThreads.size();
					int leftThrs = threads.size();
					if(runThrs>0 && leftThrs>0){
						for(int i=0;i<Math.min(leftThrs, runThrs);i++){
							BizThread fth= threads.remove(0);
							runThreads.add(fth);
							fth.start();
							System.out.println("线程 " + fth.getName()+" 启动!");
						}
					} 
				}
				 
				//休眠一秒钟
				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} 
			 }
			 
		 } 
		 		 
	}
	
	public static String getRandomString(int size) { 
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for(int i=0;i<size;i++){                
			sb.append(base.charAt(random.nextInt(base.length())));       
		}
		return sb.toString();
	}
}